<template>
    <BasicDrawer v-bind="$attrs" :okAuth="'drill:fireDrill:edit'" @register="registerDrawer" @ok="handleSubmit"
                 width="60%">
        <template #title>
            <Icon :icon="getTitle.icon" class="m-1 pr-1"/>
            <span> {{ getTitle.value }} </span>
        </template>
        <div class="fireVeIm">
            <div class="fireVideo">
                <span>
                    演练视频：
                </span>
                <video
                        width="100%"
                        height="100%"
                        :src="videoSrc"
                        controls
                        autoplay
                        muted
                        @loadeddata="onVideoLoaded"
                        @error="onVideoError"
                        type="video/mp4">
                </video>
            </div>
  
            <!-- <div class="fireImg">
                <span>
                    火情结束照片：
                </span>
                <Image v-if="imageSrc" :src="imageSrc" width="100%" height="100%"></Image>
                <img v-else src="/@/assets/images/noData.png" style="width: 150px;height:auto;" alt="">
            </div> -->
        </div>
        <BasicForm @register="registerForm"/>
        <hr />
        <div class="map-timeline-container">
            <a-timeline class="timeline">
                <!-- 遍历 1 到 6 级 -->
                <a-timeline-item v-for="level in [1, 2, 3, 4, 5, 6]" :key="level">
                    <p>第{{ level }}级灭火力量</p>
                    <!-- 查找对应级别的数据 -->
                    <p v-if="getLevelData(level)">
                      <!-- 根据 confirmed 值显示不同内容 -->
                      {{ getLevelData(level).confirmed? getLevelData(level).notifierName + ' 于 ' + getLevelData(level).confirmTime + ' 确认收到火情' : getLevelData(level).notifierName + ' 未确认' }}
                    </p>
                    <p v-else>未确认</p>
                </a-timeline-item>
            </a-timeline>
            <BaiduMap :showButtons="false" class="baidu-map"/>
        </div>
    </BasicDrawer>
  </template>
  <script lang="ts" setup name="ViewsDrillFireDrillForm">
  import { ref, unref, computed } from 'vue';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { router } from '/@/router';
  import { Icon } from '/@/components/Icon';
  import { BasicForm, FormSchema, useForm } from '/@/components/Form';
  import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';
  import { FireDrill, fireDrillSave, fireDrillForm } from '/@/api/drill/fireDrill';
  import { InFireNotificationData } from '/@/api/management/inFireNotification';
  import BaiduMap from '/@/components/BMap';
  import { Image } from 'ant-design-vue';
  import { Timeline } from 'ant-design-vue';
  
  const emit = defineEmits(['success','register']);
  
  const { t } = useI18n('drill.fireDrill');
  const { showMessage } = useMessage();
  const { meta } = unref(router.currentRoute);
  const record = ref<FireDrill>({} as FireDrill);
  
  const getTitle = computed(() => ({
    icon: meta.icon || 'i-ant-design:book-outlined',
    value: record.value.isNewRecord? t('详情') : t('详情'),
  }));
  
  const imageSrc = ref('');
  const videoSrc = ref('');
  const inFireId = ref('');
  const timelineData = ref([]);
  
  // 计算属性，对时间轴数据按 linkageLevel 排序
  const sortedTimelineData = computed(() => {
    return timelineData.value.slice().sort((a, b) => {
      return parseInt(a.linkageLevel) - parseInt(b.linkageLevel);
    });
  });
  
  // 根据级别获取数据的方法
  const getLevelData = (level: number) => {
    return sortedTimelineData.value.find(item => parseInt(item.linkageLevel) === level);
  };
  
  const inputFormSchemas: FormSchema[] = [
    {
        label: t('企业ID'),
        field: 'enterpriseId',
        show: false,
        component: 'Input',
        componentProps: {
            maxlength: 255,
        },
    },
    {
        label: t('企业名称'),
        field: 'enterpriseName',
        component: 'TreeSelect',
        componentProps: {
            maxlength: 255,
        },
    },
    {
        label: t('建筑ID'),
        field: 'buildId',
        show: false,
        component: 'Input',
        rules: [{ pattern: /^\d+$/, message: t('请输入一个正整数') }],
    },
    {
        label: t('建筑名称'),
        field: 'buildName',
        component: 'Input',
        componentProps: {
            maxlength: 100,
        },
    },
    {
        label: t('区域ID'),
        field: 'regionId',
        component: 'Input',
        show: false,
        rules: [{ pattern: /^\d+$/, message: t('请输入一个正整数') }],
    },
    {
        label: t('区域名称'),
        field: 'regionIname',
        component: 'Input',
        componentProps: {
            maxlength: 255,
        },
    },
    {
        label: t('火情名称'),
        field: 'fireName',
        component: 'Input',
        componentProps: {
            maxlength: 255,
        },
    },
    {
        label: t('详细地址'),
        field: 'location',
        component: 'Input',
        componentProps: {
            maxlength: 255,
        },
    },
    {
        label: t('火情确认时间'),
        field: 'fireConfirmTime',
        component: 'DatePicker',
        componentProps: {
            format: 'YYYY-MM-DD HH:mm',
            showTime: { format: 'HH:mm' },
        },
    },
    {
        label: t('确认用户ID'),
        field: 'fireUserId',
        show: false,
        component: 'Input',
        componentProps: {
            maxlength: 100,
        },
    },
    {
        label: t('确认用户姓名'),
        field: 'fireUserName',
        component: 'Input',
        componentProps: {
            maxlength: 100,
        },
    },
    {
        label: t('火情发起人'),
        field: 'fireInitiatorUser',
        component: 'Input',
        componentProps: {
            maxlength: 100,
        },
    },
    {
        label: t('火情发起人ID'),
        field: 'fireInitiatorUserId',
        show: false,
        component: 'Input',
        componentProps: {
            maxlength: 100,
        },
    },
    {
        label: t('救援时间'),
        field: 'rescueTime',
        component: 'DatePicker',
        show: false,
        componentProps: {
            format: 'YYYY-MM-DD HH:mm',
            showTime: { format: 'HH:mm' },
        },
    },
    {
        label: t('结束时间'),
        field: 'endTime',
        component: 'DatePicker',
        show: false,
        componentProps: {
            format: 'YYYY-MM-DD HH:mm',
            showTime: { format: 'HH:mm' },
        },
    },
    {
        label: t('创建时间'),
        field: 'createTime',
        component: 'DatePicker',
        show: false,
        componentProps: {
            format: 'YYYY-MM-DD HH:mm',
            showTime: { format: 'HH:mm' },
        },
    },
    {
        label: t('更新时间'),
        field: 'updateTime',
        component: 'DatePicker',
        show: false,
        componentProps: {
            format: 'YYYY-MM-DD HH:mm',
            showTime: { format: 'HH:mm' },
        },
    },
    {
        label: t('火情状态'),
        field: 'fireExecutionStatus',
        component: 'Input',
        componentProps: {
            maxlength: 10,
        },
    },
    {
        label: t('指战员'),
        field: 'commander',
        show: false,
        component: 'Input',
        componentProps: {
            maxlength: 255,
        },
    },
    {
        label: t('演练联动级别'),
        field: 'linkageLevel',
        show: false,
        component: 'Input',
        componentProps: {
            maxlength: 255,
        },
    },
    {
        label: t('火情结束照片ID'),
        field: 'confirmFireFileId',
        show: false,
        component: 'Input',
        componentProps: {
            maxlength: 1024,
        },
    },
    {
        label: t('纬度'),
        field: 'latitude',
        show: false,
        component: 'Input',
        componentProps: {
            maxlength: 255,
        },
    },
    {
        label: t('经度'),
        field: 'longitude',
        show: false,
        component: 'Input',
        componentProps: {
            maxlength: 255,
        },
    },
  ];
  
  const [registerForm, { resetFields, setFieldsValue, validate }] = useForm({
    labelWidth: 120,
    schemas: inputFormSchemas,
    baseColProps: { md: 24, lg: 12 },
  });
  
  const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
    setDrawerProps({ loading: true });
    await resetFields();
    const res = await fireDrillForm(data);
    console.log('res', res);
    inFireId.value = res.fireDrill.tid;
    record.value = (res.fireDrill || {}) as FireDrill;
    record.value.__t = new Date().getTime();
  
    imageSrc.value = record.value.confirmFireFile || '';
    videoSrc.value = record.value.confirmFireFile || '';
    console.log('videoSrc', videoSrc.value);
    setFieldsValue(record.value);
  
    // 调用 InFireNotificationData 接口获取时间轴数据
    try {
      const params = {mainId: inFireId.value };
      console.log('timelineResparams', params);
      const timelineRes = await InFireNotificationData(params);
      timelineData.value = timelineRes.list || [];
    } catch (error) {
      console.error('获取时间轴数据失败:', error);
    }
  
    setDrawerProps({ loading: false });
  });
  
  async function handleSubmit() {
    try {
        const data = await validate();
        setDrawerProps({ confirmLoading: true });
        const params: any = {
            isNewRecord: record.value.isNewRecord,
            tid: record.value.tid,
        };
        const res = await fireDrillSave(params, data);
        showMessage(res.message);
        setTimeout(closeDrawer);
        emit('success', data);
    } catch (error: any) {
        if (error && error.errorFields) {
            showMessage(error.message || t('common.validateError'));
        }
        console.log('error', error);
    } finally {
        setDrawerProps({ confirmLoading: false });
    }
  }
  
  const onVideoLoaded = () => {
    const video = document.querySelector('video');
    if (video && video.readyState >= video.HAVE_ENOUGH_DATA) {
        video.play().catch((error) => {
            console.error('视频播放错误:', error);
        });
    }
    console.log('视频加载完成');
  };
  const onVideoError = (event) => {
    const video = event.target;
    console.error('视频加载失败:', video.error);
    console.error('视频网络状态:', video.networkState);
    console.error('视频就绪状态:', video.readyState);
  };
  </script>
  
  <style scoped lang="less">
  .fireVeIm {
    display: flex;
    justify-content: space-around;
    align-items: center;
    margin-bottom: 5%;
  }
  .fireImg {
    width: 20%;
    height: 200px;
  }
  .fireVideo {
    width: 20%;
    height: 200px;
  }
  .map-timeline-container {
    display: flex;
  }
  .timeline,
  .baidu-map {
    width: 50%;
  }
  </style>